package com.zxd.interview.conrruentbook;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch 计数器设置
 */
public class CountDownLatchTest {

    public static void main(String[] args){
        //创建一个计数器为3的CountDownLatch
        CountDownLatch countDownLatch = new CountDownLatch(3);
        //导游线程
        new Thread(()->{
            try {
                System.out.println("导游--等待张三、李四和王五到达出发地");
                countDownLatch.await();
                System.out.println("张三、李四和王五都已经到达出发地，一起跟随导游出发去目的地旅游");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }, "Leader-thread").start();
        //张三线程
        new Thread(new CountDownLatchTask("张三", countDownLatch)).start();
        new Thread(new CountDownLatchTask("李四", countDownLatch)).start();
        new Thread(new CountDownLatchTask("王五", countDownLatch)).start();
    }

    private static class CountDownLatchTask implements Runnable {
        private String name;
        private CountDownLatch countDownLatch;

        public CountDownLatchTask(String name, CountDownLatch countDownLatch) {
            this.name = name;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            try {
                Random random = new Random();
                Thread.sleep(random.nextInt(2000));
                System.out.println(this.name + "--到达出发地");
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
